package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.UserLocation;
import com.itheima.service.mongo.UserLocationService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class UserLocationServiceImpl implements UserLocationService {
    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public void save(Double longitude, Double latitude, String addrStr, Long userId) {
        //1.通过用户id查询用户位置对象
        UserLocation userlocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class);
        if (userlocation==null) {
            //2.若没有设置过则保存
            userlocation=new UserLocation();
            userlocation.setUserId(userId);
            //设置经纬度,经度在前,纬度在后
            userlocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userlocation.setAddress(addrStr);

            userlocation.setCreated(System.currentTimeMillis());
            userlocation.setUpdated(userlocation.getCreated());
            mongoTemplate.save(userlocation);
        }else {
            //3.若设置过则更新
            userlocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userlocation.setAddress(addrStr);

            userlocation.setLastUpdated(userlocation.getUpdated());
            userlocation.setUpdated(System.currentTimeMillis());

            mongoTemplate.save(userlocation);
        }
    }

    @Override
    public List<Long> searchNear(Long userId, Integer distance) {
        //获取我的地理位置
        UserLocation userLocation = mongoTemplate.findOne(new Query(Criteria.where("userId").is(userId)), UserLocation.class);

        //圆心
        GeoJsonPoint point = userLocation.getLocation();
        //半径
        Distance radius = new Distance(distance/1000, Metrics.KILOMETERS);

        //2.创建条件对象(我坐标为圆心,距离为半径,在这个圈里用户)
        Circle circle = new Circle(point, radius);
        Query query=new Query(
                Criteria.where("location").withinSphere(circle)
        );

        //3.查询userLocation表获取用户集合
        List<UserLocation> userLocations = mongoTemplate.find(query, UserLocation.class);

        //4.遍历集合,获取每个用户id存入idList中
        List<Long> ids = userLocations.stream().map(UserLocation::getUserId).collect(Collectors.toList());

        //5.返回idList
        return ids;
    }
}
